package com.projectimport.service.impl;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.projectimport.dao.EnPlanVersionCjDao;
import com.projectimport.dao.EnResourcesDao;
import com.projectimport.dao.ProObjDao;
import com.projectimport.dao.ProTaskpredDao;
import com.projectimport.dao.XpmHumanDao;
import com.projectimport.model.EnResources;
import com.projectimport.model.ProObj;
import com.projectimport.model.ProTaskpred;
import com.projectimport.model.XpmHuman;
import com.projectimport.service.ProjectImportService;

import net.sf.mpxj.ProjectFile;
import net.sf.mpxj.Relation;
import net.sf.mpxj.Task;
@Service
public class ProjectImportServiceImpl implements ProjectImportService{

	@Resource
	private ProObjDao ProObjDao;

	@Resource
	private XpmHumanDao xpmHumanDao;

	@Resource
	private ProTaskpredDao proTaskpredDao;

	@Resource
	private EnResourcesDao enResourcesDao;

	@Resource
	private EnPlanVersionCjDao enPlanVersionCjDao;

	private final Logger logger=LoggerFactory.getLogger(this.getClass());

	@Override
	public Map<String, Object> projectimport(ProjectFile projectFile, String planVersionSid, String humanSid) {
		logger.info("----开始写入任务----");
		Map<String, Object> map=new HashMap<>();
		SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//清空该版本所有任务
		ProObjDao.deleteAllByplanVersionSid(planVersionSid);
		//取得录入人
		XpmHuman xpmHuman=xpmHumanDao.findOne(humanSid);
		List<Task>tasks=projectFile.getTasks();
		List<ProObj>proObjs=new ArrayList<>();
		for(Task task:tasks) {
			//去节点
			if(task.getChildTasks().isEmpty()) {
				List<XpmHuman> xpmHumans=xpmHumanDao.findByHumanName(task.getContact()==null?"null":task.getContact());
				ProObj proObj=new ProObj();
				proObj.setPlanVersionSid(planVersionSid);
				proObj.setObjCode(getCode(task.getID()));
				proObj.setObjName(task.getName());
				proObj.setPs(formater.format(task.getStart()));
				proObj.setPf(formater.format(task.getFinish()));
				proObj.setTaskStatus("（NS）未开始");
				proObj.setObjType("TASK");
				proObj.setTaskPeriod(new DecimalFormat("0").format(task.getDuration().getDuration()));
				proObj.setRegisterDate(new Date());
				proObj.setRegisterHuman(xpmHuman.getHumanName());
				proObj.setRegisterHumanSid(xpmHuman.getHumanSid());
				if(task.getName().indexOf("齐套")!=-1) {
					proObj.setIsFk("齐套");
					proObj.setTaskPeriod("0");
					if(task.getName().indexOf("项目齐套")!=-1) {
						proObj.setFkType("项目层次");
					}else {
						proObj.setFkType("单元层次");
					}
					//只有人员姓名存在且仅存在一个时才设置
					if(xpmHumans!=null&&xpmHumans.size()==1) {
						proObj.setFkManager(xpmHumans.get(0).getHumanName());
						proObj.setFkManagerSid(xpmHumans.get(0).getHumanSid());
					}
				}else {
					proObj.setIsFk("一般");
					if(xpmHumans!=null&&xpmHumans.size()==1) {
						proObj.setTaskManager(xpmHumans.get(0).getHumanName());
						proObj.setTaskManagerSid(xpmHumans.get(0).getHumanSid());
					}
				}
				if(task.getName().indexOf("里程碑")!=-1) {
					proObj.setTaskType("完成里程碑");
					proObj.setTaskPeriod("0");
				}else {
					proObj.setTaskType("任务作业");
				}
				proObjs.add(proObj);
			}
		}
		ProObjDao.save(proObjs);
		map.put("objCount", proObjs.size());
		logger.info("----任务写入成功----");
		map.put("taskLogicCount", taskLogic(proObjs, tasks,xpmHuman));
		return map;
	}

	/**
	 * 根据任务id生成编号
	 * @param taskId
	 * @return
	 */
	private String getCode(int taskId) {
		String code;
		if (taskId>1000) {
			code=String.valueOf(taskId);
		}else {
			code=String.valueOf(1000+taskId);
		}
		return code;
	}


	private int taskLogic(List<ProObj> proObjs,List<Task> tasks,XpmHuman xpmHuman) {
		logger.info("----开始插入逻辑关系----");
		List<ProTaskpred> proTaskpreds=new ArrayList<>();
		Map<String, String> objCodeandSid=new HashMap<>();
		for(ProObj proObj:proObjs) {
			objCodeandSid.put(proObj.getObjCode(), proObj.getObjSid());
		}
		for(Task task:tasks) {
			List<Relation> predeList=task.getPredecessors();
			if(!predeList.isEmpty()) {
				for(Relation relation:predeList) {
					ProTaskpred proTaskpred=new ProTaskpred();
					proTaskpred.setPredTaskSid(objCodeandSid.get(getCode(relation.getTargetTask().getID())));
					proTaskpred.setTaskSid(objCodeandSid.get(getCode(task.getID())));
					proTaskpred.setPredType("FS");
					proTaskpred.setRegisterdate(new Date());
					proTaskpred.setRegisterhuman(xpmHuman.getHumanName());
					proTaskpreds.add(proTaskpred);
				}
			}
		}
		proTaskpredDao.save(proTaskpreds);
		logger.info("----逻辑关系插入结束----");
		return proTaskpreds.size();
	}

	private int saveEnResources(String planVersionSid,List<net.sf.mpxj.Resource> resources,XpmHuman xpmHuman) {
		logger.info("----开始导入资源----");
		List<String> objResourcesNameList= enResourcesDao.findByplanVersionSid(planVersionSid);
		List<EnResources> mppResources=new ArrayList<>();
		int maxCode=Integer.parseInt(enResourcesDao.getMaxCode(planVersionSid));
		for(net.sf.mpxj.Resource resource:resources) {
			if(!objResourcesNameList.contains(resource.getName())) {
				maxCode+=10;
				EnResources enResources=new EnResources();
				enResources.setResourcesCode("R"+String.valueOf(maxCode));
				enResources.setResourcesName(resource.getName());
				enResources.setIsActive("1");
				enResources.setMaxSupply(String.valueOf(resource.getMaxUnits().intValue()/100));
				enResources.setRegisterDate(new Date());
				enResources.setRegisterHuman(xpmHuman.getHumanName());
				enResources.setRegisterHumanSid(xpmHuman.getHumanSid());
				enResources.setXpmobsSid(enPlanVersionCjDao.findOne(planVersionSid).getProjSid());
				mppResources.add(enResources);
			}
		}
		enResourcesDao.save(mppResources);
		logger.info("----资源导入成功----");
		return mppResources.size();
	}



}
